<?php

/**
 * 访问Action的控制器<p/>
 * @catepory 【核心框架】
 * @author zhouhaichao(a)2008.sina.com
 * @version 1.0
 * @copyright (c) 2008
 * @date 2013-2-21
 */
class ActionInvoker
{
    /**
     * 请求代处理
     * @param Request $request 请求对象
     * @param Config $config 配置信息
     * @return array|mixed
     */
    public static function invoke(Request $request, Config $config)
    {

        $ctlInfo = $request->getController();

        $controllerFile = $ctlInfo["path"];
        $controllerClassName = $ctlInfo["controller"];
        $controllerMethod = $ctlInfo["method"];
        $controllerMethodParam = $ctlInfo["param"];
        $mimeType = $ctlInfo["mimeType"];

        if (file_exists($controllerFile)) {
            require_once($controllerFile);
            if (class_exists($controllerClassName)) {
                // remap是不允许外部直接访问的。
                if ($controllerMethod == "_remap" || preg_match('/_.*/', $controllerMethod)) {
                    return array("code" => 404);
                }
                try {
                    return array(
                        "code" => 200,
                        "view" => invokeMethod($controllerClassName, array($request), "_remap", array($controllerMethod, $controllerMethodParam))
                    );
                } catch (Exception $e) {
                    return array("code" => 500, "view" => $e);
                }
            } else {
                return array("code" => 404, "view" => "the class $controllerFile not found !");
            }
        } else {
            return array("code" => 404, "view" => "the file $controllerClassName not found !");
        }
    }
}